package com.sj.security;

import cn.hutool.json.JSONUtil;
import com.sj.common.lang.ApiResult;
import com.sj.common.lang.RedisConst;
import com.sj.entity.User;
import com.sj.service.UserService;
import com.sj.utils.MineUtils;
import com.sj.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2022-03-10
 * Time: 下午 15:21
 * Description: 退出登录成功处理器
 *
 * @author xiaoqi
 * @since 2022-03-10
 */
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private MineUtils mineUtils;

    @Autowired
    private UserService userService;

    @Value("${know.tokenKey}")
    private String userTokenKey;

    @Value("${know.authKey}")
    private String authKey;

    @Override
    @CacheEvict(cacheNames = {"article-list" , "fix-type", "article-num-data"}, keyGenerator = RedisConst.REDIS_SJ_KEY_GENERATOR, allEntries = true)
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        Integer uId = mineUtils.getUidByToken();
        User user = userService.getById(uId);
        if (user != null) {
            // 删除用户的token 以及 权限信息
            redisUtils.del(userTokenKey + "-" + user.getUsername(), authKey + "-" + user.getUsername());
        }
        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(request, response, authentication);
        }

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(JSONUtil.toJsonStr(ApiResult.success("退出成功")).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}